/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
$(function () {
    var shop_id = $("#shop").data("id"),
            // buttons
            saveUserInfo = $("#saveUserInfo"),
            cancelInfoEdit = $("#cancelInfoEdit"),
            showEditPanel = $("#showEditPanel"),
            displayInfo = $("#displayInfo"),
            editInfo = $("#editInfo"),
            addImageBtn = $("#addImageBtn"),
            upload_btn_default = '<i class="fa fa-check mr10"></i>保存图片',
            upload_btn_process = '<i class="fa fa-spin fa-spinner mr10"></i>上传中...',
            imageContainer = $("#image-container"),
            active_tab = $("#shop").data("tab");
    /**
     * 设置当前显示的tab页
     */
    if (active_tab !== '') {
        $("#li-" + active_tab).addClass("active");
        $("#tab-" + active_tab).addClass("active");
    } else {
        $("#li-info").addClass("active");
        $("#tab-info").addClass("active");
    }
    /**
     * 刷新页面并跳转到相应tab
     */
    var url = location.href.split('?tab=')[0];
    var getUrl = {
        info: url + "?tab=info",
        images: url + "?tab=images",
        fund: url + "?tab=fund",
        loans: url + "?tab=loans",
        invests: url + "?tab=invests"
    };
    var refresh = function (tab) {
        location.href = getUrl[tab];
    };
    /**
     * 取消用户编辑
     */
    cancelInfoEdit.on("click", function () {
        editInfo.hide();
        saveUserInfo.hide();
        cancelInfoEdit.hide();
        showEditPanel.show();
        displayInfo.show();
    });
    /**
     * 显示用户资料编辑面板
     */
    showEditPanel.on("click", function () {
        displayInfo.hide();
        showEditPanel.hide();
        saveUserInfo.show();
        cancelInfoEdit.show();
        editInfo.show();
    });
    
    // 初始化图片预览弹出框
    var initPopUp = function () {
        $('.image img').magnificPopup({
            type: 'image',
            callbacks: {
                beforeOpen: function (e) {
                    // we add a class to body to indicate overlay is active
                    // We can use this to alter any elements such as form popups
                    // that need a higher z-index to properly display in overlays
                    $('body').addClass('mfp-bg-open');

                    // Set Magnific Animation
                    this.st.mainClass = 'mfp-zoomIn';

                    // Inform content container there is an animation
                    this.contentContainer.addClass('mfp-with-anim');
                },
                afterClose: function (e) {
                    $('body').removeClass('mfp-bg-open');
                },
                elementParse: function (item) {
                    // Function will fire for each target element
                    // "item.el" is a target DOM element (if present)
                    // "item.src" is a source that you may modify
                    item.src = item.el.data('url');
                }
            },
            removalDelay: 200 //delay removal by X to allow out-animation
        });
    };
    /**
     * 初始化图片上传控件
     */
    var initUploader = function () {
        var doUploadBtn = $("#doUploadBtn"), document = null;
        /**
         * 弹出文件选择框
         */
        $('#upZone').click(function () {
            $('#fileInput').click();
        });
        $('#fileInput').on("change", function (e) {
            var files = e.target.files;
            if (!files.length || !window.FileReader) {
                return; // no file selected, or no FileReader support
            }
            document = files[0];
            $("#fileName").val(document.name);
            if (/^image/.test(document.type)) {
                var reader = new FileReader();
                var img = new Image();
                reader.readAsDataURL(document);
                reader.onload = function (e) {
                    img.src = e.target.result;
                    setTimeout(function () {
                        if (img.width === 800 && img.height === 800) {
                            $("#imagePreview").html($('<img class="h-150"/>').attr('src', e.target.result));
                        } else {
                            $("#doUploadBtn").css("display", "none");
                            alert("选择的图片必须是800*800!");
                            location.reload();
                        }
                    }, 1000);
                }
            }
        });
        /**
         * 保存图片：触发上传
         */
        doUploadBtn.on("click", function () {
            if (document === null) {
                alert("尚未选择图片");
            } else {
                $('form[name=uploadForm]').trigger('submit');
            }
        });
        /**
         *  上传文件
         */
        $('form[name=uploadForm]').on('submit', function (event) {
            event.stopPropagation();
            event.preventDefault();

            var url = 'pointsystem/upload';
            var formData = new FormData();
            formData.append("file", document);
            formData.append("name", $("#fileName").val());
            formData.append("desc", $("#description").val());
            formData.append("realm", 'USER');
            formData.append("cid", $("#commodityId").data("id"));
            formData.append("id", user_id);

            doUploadBtn.prop("disabled", true).html(upload_btn_process);
            $.ajax({
                url: url,
                data: formData,
                processData: false,
                contentType: false,
                type: 'POST',
                success: function (res) {
                    doUploadBtn.html(upload_btn_default).prop("disabled", false);
                    if (res.success) {
                        alert("图片上传成功！");
                        refresh("images");
                    } else {
                        alert(res.message);
                    }
                }
            }).fail(function () {
                alert('图片上传失败：服务器错误');
            });
        });
    };

});

